package com.hzit.pay.center.service.impl;

import com.hzit.pay.center.constant.RedisKeyConstant;
import com.hzit.pay.center.exception.BizException;
import com.hzit.pay.center.mapper.MchPayChannelInfoMapper;
import com.hzit.pay.center.model.MchPayChannelInfo;
import com.hzit.pay.center.service.IPayChannelService;
import com.pay.center.common.enums.PayMethodEnum;
import com.pay.center.common.resp.PayMethodData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 商户支付渠道接口实现
 */
@Service
public class PayChannelServiceImpl implements IPayChannelService {

    @Autowired
    private ValueOperations<String,Object> valueOperations;

    @Autowired
    private MchPayChannelInfoMapper payChannelInfoMapper;


    @Override
    public List<PayMethodData> queryByMchId(String mchId) {

        //1.先从缓存获取
        String redisKey = RedisKeyConstant.MCH_PAY_CHANNEL + mchId;
        List<PayMethodData> payMethodDataList = (List<PayMethodData>)valueOperations.get(redisKey);

        if (!CollectionUtils.isEmpty(payMethodDataList)){
            return payMethodDataList;
        }

        List<MchPayChannelInfo> mchPayChannelInfoList =  payChannelInfoMapper.queryByMchId(mchId);
        if (CollectionUtils.isEmpty(mchPayChannelInfoList)){

            throw new BizException(); //TODO
        }

        payMethodDataList = new ArrayList<PayMethodData>();
        for (MchPayChannelInfo mchPayChannelInfo :mchPayChannelInfoList){
            PayMethodData payMethodData = new PayMethodData();
            payMethodData.setImgUrl("");
            payMethodData.setPayChannel(mchPayChannelInfo.getPayChannel());
            payMethodData.setPayMethod(mchPayChannelInfo.getPayMethod());
            payMethodData.setPayMethodName(PayMethodEnum.ALIPAY_TRADE_WAP_PAY.getMsg(mchPayChannelInfo.getPayMethod()));
            payMethodDataList.add(payMethodData);
        }

        //存入缓存
        valueOperations.set(redisKey,payMethodDataList,12, TimeUnit.HOURS);

        return payMethodDataList;
    }

    @Override
    public MchPayChannelInfo queryByMchIdAndPayMethod(String mchId, String payChannel, String payMethod) {

        MchPayChannelInfo mchPayChannelInfo = payChannelInfoMapper.queryByMchIdAndChannel(mchId,payChannel,payMethod);

        return mchPayChannelInfo;
    }
}
